from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ViewSetMixin, GenericViewSet
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.decorators import api_view, action
from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework import status

from app_service.models.school_model import School, Student
from app_service.serializers.school_serializer import SchoolSerializer


@csrf_exempt
def school_api(request: HttpRequest, pk: int):
    school = None
    if pk > 0:
        try:
            school = School.objects.get(pk=pk)
        except Exception as e:
            print(e)
            return HttpResponse(status=status.HTTP_404_NOT_FOUND)
        pass
    else:
        if request.method in ('PUT', 'DELETE'):
            return HttpResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED)
        pass

    if request.method == 'GET':  # select
        if pk <= 0:
            schools = School.objects.all()
            serializers = SchoolSerializer(instance=schools, many=True)
            return Response(serializers.data)
        else:
            serializer = SchoolSerializer(instance=school)
            return Response(data=serializer.data)
        pass
    elif request.method == 'POST':  # insert
        if pk <= 0:
            data = JSONParser().parse(request)
            serializer = SchoolSerializer(data=data)
            if serializer.is_valid():  # 验证
                serializer.save()
                return Response(data=serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return HttpResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED)
        pass
    elif request.method == 'PUT':  # update
        data = JSONParser().parse(request)
        serializer = SchoolSerializer(instance=school, data=data)
        if serializer.is_valid():  # 验证
            serializer.save()
            return Response(data=serializer.data)
        return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':  # delete
        school.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

    pass


class SchoolsAPI(ListCreateAPIView):
    queryset: QuerySet = School.objects.all()
    serializer_class = SchoolSerializer
    pass


class SchoolAPI(RetrieveUpdateDestroyAPIView):
    queryset: QuerySet = School.objects.all()
    serializer_class = SchoolSerializer
    pass


class SchoolViewSet(ModelViewSet):
    queryset = School.objects.all()
    serializer_class = SchoolSerializer

    lookup_field = 'id'

    authentication_classes = [
        # BasicAuthentication,
        SessionAuthentication,
    ]
    permission_classes = [
        IsAuthenticated,
    ]

    def get_authenticators(self):
        if self.action == 'no_auth':
            return []
        return [auth() for auth in self.authentication_classes]

    def get_permissions(self):
        if self.action == 'no_auth':
            return []
        return [permission() for permission in self.permission_classes]

    @action(methods=['post'], detail=False)
    def no_auth(self):
        response = Response()
        return response
